self.timers = {}

self.onmessage = function(event) {
  const { action, id, interval } = event.data
  switch (action) {
    case 'startTimer':
      startTimer(id, interval)
      break
    case 'stopTimer':
      stopTimer(id)
      break
    case 'stopAllTimers':
      stopAllTimers()
      break
  }
}

function startTimer(id, interval) {
  if (!self.timers[id]) {
    self.timers[id] = setInterval(() => {
      self.postMessage({ id })
    }, interval)
  }
}

function stopTimer(id) {
  if (self.timers[id]) {
    clearInterval(self.timers[id])
    delete self.timers[id]
  }
}

function stopAllTimers() {
  Object.keys(self.timers).forEach(id => {
    clearInterval(self.timers[id])
  })
  self.timers = {}
}

